

LoadedTilesets = {"default": new Image()}
LoadedTilesets.default.onload = () -> console.log "Loaded Default Tiles"
LoadedTilesets.default.src = "../data/tiles/default@tiles.png"
# img.onload, pertinent

###
# -class Tileset
# Loads and manages tilesets. Can be created more than once with the
# same tileset.<br/>
# Makes use of global variables `LoadedTilesets` and `TilePaths`
###

class Tileset
  constructor: (@path) ->
    @img = new Image()
    This = this
    if not LoadedTilesets.hasOwnProperty @path
      #console.log("Loading "+@path+"...")
      LoadedTilesets[@path] = new Image()
      LoadedTilesets[@path].src = TilePaths[@path]
      LoadedTilesets[@path].onload = () ->
        This.img = LoadedTilesets[This.path]
        #console.log("Loaded "+This.path+"!")
    @img = LoadedTilesets[@path]
  draw: (screen,x,y,offx,offy,deltax,deltay) ->
      ts = MouseFollower.prototype.TileSize*2
      destx = ts/2*x - deltax
      desty = ts/2*y+ts/4*(x%2) - deltay
      # todo, if dest{x,y} in screen_rect then...
      screen.drawImage(@img,ts*offx,ts*offy,ts,ts, destx,desty, ts,ts)

###
# -class Tile
# Simple class meant to be serialized within a Map class
# only contains the tileset reference, and offsets within
# the tileset
###

class Tile
  constructor: (@tileset,@offx,@offy,@blocks) ->
    if typeof @tileset is typeof 'str'
      @tileset = new Tileset(@tileset)
    if @blocks is undefined
      @blocks = false
  draw: (screen,x,y,dx,dy) ->
    @tileset.draw(screen,x,y,@offx,@offy,dx,dy)
  toJSON: () ->
    return {
        type:"Tile",path:@tileset.path,
        offx:@offx,offy:@offy,
        blocks:@blocks}
  load: (json) ->
    @tileset = new Tileset(json.path)
    @offx = json.offx
    @offy = json.offy
    @blocks = json.blocks
    if @blocks is undefined
      @blocks = false
    return this
